{% extends "base.html" %}
{% block title %}中间件属性设置 - IT资产管理平台{% endblock %}

{% block content %}
<div class="content-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
  <!-- 左侧标题区域 -->
  <div class="header-title" style="display: flex; align-items: center;">
    <h2>中间件属性设置</h2>
  </div>
  <!-- 右侧操作区域 -->
  <div class="header-actions">
    <button id="addAttrBtn" class="btn btn-primary" style="padding: 6px 12px;">添加属性</button>
  </div>
</div>

<!-- 中间件属性列表表格 -->
<div class="table-wrapper">
  <table class="property-table">
    <thead>
      <tr>
        <th>属性名称</th>
        <th>属性类型</th>
        <th>是否必填</th>
        <th>是否唯一</th>
        <th>提示文本</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      {% for attr in middleware_properties|default([]) %}
      <tr data-id="{{ attr.id }}" data-record='{{ attr|tojson|safe }}'>
        <td>{{ attr.name }}</td>
        <td>{{ attr.type }}</td>
        <td>{{ "是" if attr.required else "否" }}</td>
        <td>{{ "是" if attr.unique_attr else "否" }}</td>
        <td>{{ attr.placeholder }}</td>
        <td>
          <button class="editAttrBtn btn btn-sm btn-primary" data-id="{{ attr.id }}">修改</button>
          <button class="deleteAttrBtn btn btn-sm btn-danger" data-id="{{ attr.id }}">删除</button>
        </td>
      </tr>
      {% endfor %}
    </tbody>
  </table>
</div>

<!-- 添加属性弹窗 -->
<div id="attrModal" class="modal">
  <div class="modal-content">
    <span class="close" id="attrModalClose">&times;</span>
    <h3>添加中间件属性</h3>
    <form id="attrAddForm" method="post" action="{{ url_for('add_middleware_attribute') }}">
      <div class="form-group">
        <label for="attr_name">属性名称*</label>
        <input type="text" name="name" id="attr_name" required>
      </div>
      <div class="form-group">
        <label for="attr_type">属性类型*</label>
        <select name="type" id="attr_type" required>
          <option value="">请选择类型</option>
          <option value="文本">文本</option>
          <option value="数字">数字</option>
          <option value="IP">IP</option>
          <option value="MAC">MAC</option>
          <option value="日期">日期</option>
          <option value="时间">时间</option>
          <option value="password">password</option>
          <option value="邮箱">邮箱</option>
          <option value="布尔">布尔</option>
        </select>
      </div>
      <div class="form-group checkbox-group">
        <label>是否必填</label>
        <input type="checkbox" name="required" value="1">
        <label>是否唯一</label>
        <input type="checkbox" name="unique_attr" value="1">
      </div>
      <div class="form-group">
        <label for="placeholder">提示文本（可选）</label>
        <input type="text" name="placeholder" id="placeholder">
      </div>
      <div class="form-group buttons">
        <button type="submit" class="btn btn-success">确认</button>
        <button type="button" id="attrCancelBtn" class="btn btn-secondary">取消</button>
      </div>
    </form>
  </div>
</div>

<!-- 修改属性弹窗 -->
<div id="editAttrModal" class="modal">
  <div class="modal-content">
    <span class="close" id="editAttrModalClose">&times;</span>
    <h3>修改中间件属性</h3>
    <form id="attrEditForm" method="post">
      <div class="form-group">
        <label for="edit_attr_name">属性名称*</label>
        <input type="text" name="name" id="edit_attr_name" required>
      </div>
      <div class="form-group">
        <label for="edit_attr_type">属性类型*</label>
        <select name="type" id="edit_attr_type" required>
          <option value="">请选择类型</option>
          <option value="文本">文本</option>
          <option value="数字">数字</option>
          <option value="IP">IP</option>
          <option value="MAC">MAC</option>
          <option value="日期">日期</option>
          <option value="时间">时间</option>
          <option value="password">password</option>
          <option value="邮箱">邮箱</option>
          <option value="布尔">布尔</option>
        </select>
      </div>
      <div class="form-group checkbox-group">
        <label>是否必填</label>
        <input type="checkbox" name="required" id="edit_required" value="1">
        <label>是否唯一</label>
        <input type="checkbox" name="unique_attr" id="edit_unique_attr" value="1">
      </div>
      <div class="form-group">
        <label for="edit_placeholder">提示文本（可选）</label>
        <input type="text" name="placeholder" id="edit_placeholder">
      </div>
      <div class="form-group buttons">
        <button type="submit" class="btn btn-success">确认</button>
        <button type="button" id="editAttrCancelBtn" class="btn btn-secondary">取消</button>
      </div>
    </form>
  </div>
</div>
{% endblock %}

{% block scripts %}
{{ super() }}
<script>
document.addEventListener("DOMContentLoaded", function(){
  // 将后端传入的 middleware 属性数据转换为前端对象
  //var propertiesData = {{ middleware_properties|default([])|tojson|safe }};
  var builtInFields = ["id", "data", "created_at", "updated_at"];

  // ---------------------- 添加中间件属性功能 ----------------------
  var attrModal = document.getElementById("attrModal");
  var addAttrBtn = document.getElementById("addAttrBtn");
  var attrModalClose = document.getElementById("attrModalClose");
  var attrCancelBtn = document.getElementById("attrCancelBtn");
  var attrAddForm = document.getElementById("attrAddForm");

  if (addAttrBtn) {
    addAttrBtn.onclick = function() {
      attrModal.style.display = "block";
    };
  }
  if (attrModalClose) {
    attrModalClose.onclick = function() {
      attrModal.style.display = "none";
    };
  }
  if (attrCancelBtn) {
    attrCancelBtn.onclick = function() {
      attrModal.style.display = "none";
    };
  }
  window.onclick = function(event) {
    if (event.target === attrModal) {
      attrModal.style.display = "none";
    }
  };

  // 辅助函数：清除错误提示
  function clearErrors(form) {
    form.querySelectorAll('.error-message').forEach(function(el) {
      el.remove();
    });
  }
  // 辅助函数：显示错误提示
  function showError(field, message) {
    var formGroup = field.parentElement;
    var errorSpan = document.createElement("span");
    errorSpan.className = "error-message";
    errorSpan.style.color = "red";
    errorSpan.style.fontSize = "12px";
    errorSpan.textContent = message;
    formGroup.appendChild(errorSpan);
  }

  // 添加属性表单提交事件
  attrAddForm.onsubmit = function(e) {
    e.preventDefault();
    clearErrors(attrAddForm);
    var nameField = attrAddForm.elements["name"];
    var typeField = attrAddForm.elements["type"];
    var builtInFields = ["id", "data", "created_at", "updated_at"];
    var valid = true;
    var newName = nameField.value.trim();
    if (!nameField.value.trim()) {
      showError(nameField, "属性名称为必填项");
      valid = false;
    }
    // 检查内置字段（忽略大小写）
    if (builtInFields.indexOf(newName.toLowerCase()) !== -1) {
      showError(nameField, "此名称为内置字段，请更换");
      valid = false;
    }
    if (!typeField.value.trim()) {
      showError(typeField, "属性类型为必选");
      valid = false;
    }
    if (!valid) return false;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", attrAddForm.getAttribute("action"), true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        var res = JSON.parse(xhr.responseText);
        if (res.success) {
          location.reload();
        } else {
          alert("添加失败：" + res.message);
        }
      }
    };
    xhr.send(new FormData(attrAddForm));
  };

  // 绑定删除属性事件
  document.querySelectorAll('.deleteAttrBtn').forEach(function(button) {
    button.addEventListener('click', function() {
      var attrId = this.getAttribute("data-id");
      if (confirm("确定要删除该属性吗？")) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "{{ url_for('delete_middleware_attribute', prop_id=0) }}".replace("0", attrId), true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.onreadystatechange = function() {
          if (xhr.readyState === 4 && xhr.status === 200) {
            location.reload();
          }
        };
        xhr.send();
      }
    });
  });

  // ---------------------- 修改中间件属性功能 ----------------------
  var editAttrModal = document.getElementById("editAttrModal");
  var editAttrModalClose = document.getElementById("editAttrModalClose");
  var editAttrCancelBtn = document.getElementById("editAttrCancelBtn");
  var attrEditForm = document.getElementById("attrEditForm");
  var currentAttrId = null;

  document.querySelectorAll('.editAttrBtn').forEach(function(button) {
    button.addEventListener('click', function() {
      var row = this.closest('tr');
      currentAttrId = row.getAttribute('data-id');
      var recordJson = row.getAttribute('data-record');
      var record = {};
      if(recordJson) {
        record = JSON.parse(recordJson);
      }
      // 填充编辑表单
      attrEditForm.elements["name"].value = record.name || "";
      attrEditForm.elements["type"].value = record.type || "";
      attrEditForm.elements["placeholder"].value = record.placeholder || "";
      attrEditForm.elements["required"].checked = record.required ? true : false;
      attrEditForm.elements["unique_attr"].checked = record.unique_attr ? true : false;
      editAttrModal.style.display = "block";
    });
  });
  if (editAttrModalClose) {
    editAttrModalClose.onclick = function() {
      editAttrModal.style.display = "none";
    };
  }
  if (editAttrCancelBtn) {
    editAttrCancelBtn.onclick = function() {
      editAttrModal.style.display = "none";
    };
  }
  window.onclick = function(event) {
    if (event.target === editAttrModal) {
      editAttrModal.style.display = "none";
    }
  };

  attrEditForm.onsubmit = function(e) {
    e.preventDefault();
    clearErrors(attrEditForm);
    var nameField = attrEditForm.elements["name"];
    var valid = true;
    var newName = nameField.value.trim();
    if (!newName) {
      showError(nameField, "属性名称为必填项");
      valid = false;
    }
    if (builtInFields.indexOf(newName.toLowerCase()) !== -1) {
      showError(nameField, "此名称为内置字段，请更换");
      valid = false;
    }
    var typeField = attrEditForm.elements["type"];
    if (!typeField.value.trim()) {
      showError(typeField, "属性类型为必选");
      valid = false;
    }
    if (!valid) return false;
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "{{ url_for('update_middleware_attribute', prop_id=0) }}".replace("0", currentAttrId), true);
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        var res = JSON.parse(xhr.responseText);
        if (res.success) { editAttrModal.style.display = "none"; location.reload(); }
        else { alert("修改失败：" + res.message); }
      }
    };
    xhr.send(new FormData(attrEditForm));
  };
});
</script>
{% endblock %}
